<template>
  <view class="order-comtainer">
    <PinCustomBar />
    <!-- tabs -->
    <view class="tabs">
      <text class="item" v-for="(item, index) in orderTabs" :key="item.title" @tap="() => {
        activeIndex = index
        item.isRender = true
      }
        ">
        {{ item.title }}
      </text>
      <!-- 游标 -->
      <view class="cursor" :style="{ left: activeIndex * 25 + '%' }"></view>
    </view>

    <scroll-view @scrolltolower="onScrolltolower" refresher-enabled @refresherrefresh="onRefresherrefresh"
      :refresher-triggered="isTriggered" scroll-y class="order-list-comtainer">
      <navigator class="spu_goods" v-for="item in list" :key="item.id_" :url="`/pages/order/orderDetail?id=${item.id_}`">
        <view class="order-code_">{{ item.code_ }}</view>
        <view class="order-goods-content">
          <image class="spu_goods_img" v-for="goods in item.item_list_" :key="goods.goods_id_" :src="goods.product_img_"
            mode="aspectFit" />
          <view v-if="item.item_list_.length == 1" class="spu_goods_name ellipsis">{{ item.item_list_[0].goods_name_ }}
          </view>
        </view>
        <view class="spu_goods_footer">
          <view class="spu_goods_price">合计：<text class="price">￥{{ item.order_total_.toFixed(2) }}</text></view>
          <view class="spu_goods_price">待付：<text class="price">￥{{ item.order_total_.toFixed(2) }}</text></view>
        </view>
        <view class="spu_goods_operate">
          <button v-if="item.hasDel" size="mini" plain class="btn btn-del" @tap.stop="del(item)"
            hover-class="button-hover">删除</button>
          <button v-if="item.hasAgain" size="mini" plain class="btn btn-buy-again" @tap.stop="buyAgain(item)"
            hover-class="button-hover">再来一单</button>
          <button v-if="item.hasPay" size="mini" plain class="btn btn-go-pay" @tap.stop="goPay(item)"
            hover-class="button-hover">去付款</button>
        </view>
      </navigator>
      <view class="loading-txt">
        {{ finished ? "没有更多数据了" : "正在加载..." }}
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import PNumber from "number-precision"
import { onMounted, ref } from "vue"
import type { searchListQuery, orderlistData } from '@/types/order';
import Apis from "@/services/modules/order"
import { useMemberStore, useOrderStore } from "@/stores";

const { profile } = useMemberStore()
const { setOrder } = useOrderStore()

const searchParams: Required<searchListQuery> & { mult_finance_status_: string } = {
  showCount: 20,
  currentPage: 1,
  mult_finance_status_: ''
}

const list = ref<orderlistData[]>([])
const finished = ref(false)

onMounted(() => {
  getOrderListData()
})

// 获取页面参数
const query = withDefaults(defineProps<{
  type: number
}>(), {
  type: 1
})

const getOrderListData = async () => {

  if (finished.value) {
    return uni.showToast({
      title: '没有更多数据了',
      icon: 'none',
      mask: true
    })
  }

  const { data } = await Apis.getOrderList(searchParams)

  data.pdList.map(item => {
    // 待付金额
    item.waitPay = PNumber.minus(PNumber.minus(item.order_total_, item.income_), item.income_ing_);
    // 付款状态
    item.needPay = (item.finance_status_ === 1 || item.finance_status_ === 50) && item.waitPay > 0;
    // 删除状态
    item.hasDel = (item.form_status_ === 100 && item.finance_status_ === 100) || item.form_status_ === 999;
    // 再次购买 状态
    item.hasAgain = item.type_ !== 3;
    // 付款状态
    item.hasPay = item.needPay && !(item.tax_type_ === null && !!item.tax_status_);

  })

  list.value?.push(...data.pdList)

  if (searchParams.currentPage < data.totalPage) {
    searchParams.currentPage++
  } else {
    finished.value = true
  }
}

const onScrolltolower = () => {
  getOrderListData()
}

/* 下拉刷新 */
const isTriggered = ref(false)
const onRefresherrefresh = async () => {
  isTriggered.value = true
  list.value = []
  finished.value = false
  Object.assign(searchParams, {
    currentPage: 1,
    showCount: 20,
    mult_finance_status_: ''
  })
  await getOrderListData()
  isTriggered.value = false
}

// 再次购买
const buyAgain = async (orderData: orderlistData) => {
  const params: any = [];
  const anotherCart: any = {};

  orderData.item_list_.forEach(item => {
    // 限制值允许常规商品加入
    if (item.type_ === 1 || item.type_ === 4) {
      params.push({
        company_id_: profile?.loginUser.company_id_,//公司id
        product_id_: item.product_id_, //规格id
        goods_id_: item.goods_id_, //商品id
        number_: item.number_,//数量
        unit_id_: item.unit_id_ // 单位id
      });

      // 记录订单商品
      if (!anotherCart[item.goods_id_]) {
        anotherCart[item.goods_id_] = [];
      }
      anotherCart[item.goods_id_].push(item.product_id_);
    }
  });

  const { data } = await Apis.buyAgain(JSON.stringify(params))

  switch (data.type_) {
    case 3:
      uni.showModal({
        title: '提示',
        content: '当前订单商品已下架\r\n暂不可购买',
        showCancel: false,
        confirmText: "知道了"
      })
      break;
    case 2:
      uni.showModal({
        title: '提示',
        content: '当前订单商品已下架\r\n暂不可购买',
        showCancel: false,
        confirmText: "知道了"
      })
      break;
    case 1:
      uni.switchTab({ url: '/pages/cart/cart' })
      break;
  }

}

// 去付款
const goPay = (item: orderlistData) => {
  uni.navigateTo({ url: '/pages/order/pay' })
}

// 删除
const del = (item: orderlistData) => {
  uni.showModal({
    title: '提示',
    content: `是否删除订单\r\n【${item.code_}】?`,
    showCancel: true,
    success: async ({ confirm, cancel }) => {
      if (confirm) {
        await Apis.delOrderById(item.id_)
        onRefresherrefresh()
      }
    }
  })
}

// tabs 数据
const orderTabs = ref([
  { orderState: 0, title: '全部', isRender: false },
  { orderState: 1, title: '待付款', isRender: false },
  { orderState: 2, title: '待收货', isRender: false },
  { orderState: 3, title: '已完成', isRender: false },
])

// 高亮下标
const activeIndex = ref(orderTabs.value.findIndex((v) => v.orderState === Number(query.type)))
// 默认渲染容器
orderTabs.value[activeIndex.value].isRender = true

</script>

<style lang="scss">
page {
  background: #f7f7f7;
}

// tabs
.tabs {
  display: flex;
  justify-content: space-around;
  line-height: 60rpx;
  margin: 0 10rpx;
  background-color: #fff;
  box-shadow: 0 4rpx 6rpx rgba(240, 240, 240, 0.6);
  position: relative;
  z-index: 9;

  .item {
    flex: 1;
    text-align: center;
    padding: 20rpx;
    font-size: 28rpx;
    color: #262626;
  }

  .cursor {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 25%;
    height: 6rpx;
    padding: 0 50rpx;
    background-color: #27ba9b;
    /* 过渡效果 */
    transition: all 0.4s;
  }
}

.order-comtainer {
  height: 100vh;
  display: flex;
  flex-direction: column;

  .order-list-comtainer {
    flex: 1;
  }

  .spu_goods {
    padding: 12px;
    width: calc(100% - 24px);
    margin: auto;
    margin-bottom: 12px;
    background-color: #fff;

    .order-code_ {
      font-size: 16px;
      font-weight: 600;
      padding-bottom: 4px;
      //border-bottom: 1px solid $uni-border-color;
    }

    .order-goods-content {
      display: flex;
    }

    .spu_goods_img {
      width: 100px;
      height: 100px;
      margin-right: 6px;
    }

    .spu_goods_name {
      $padding: 4px;
      padding: $padding ;
      width: calc(100% - 2 * $padding);
      font-size: 14px;
    }

    .spu_goods_footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 4px 4px 8px;

      .spu_goods_price {
        font-size: 14px;

        .price {
          font-size: 18px;
        }

        &:last-child {
          .price {
            color: red;
            font-size: 18px;
            font-weight: bold;
          }
        }
      }
    }

    .spu_goods_operate {
      display: flex;
      justify-content: flex-end;
      padding: 0 4px;

      @mixin btnStyle($color ) {
        border-color: $color;
        background-color: $color;
        color: #fff;
        margin-left: 6px;
        margin-right: 0;
      }

      .btn-buy-again {
        @include btnStyle($uni-color-success)
      }

      .btn-del {
        @include btnStyle($uni-color-error)
      }

      .btn-go-pay {
        @include btnStyle($uni-color-warning)
      }
    }


  }
}

.loading-txt {
  text-align: center;
  padding: 6px 0 24px;
}
</style>

